<template>
  <div class="user-list-container">
    <header-search-form
      :searchFormData="searchForm"
      @search="search"
      :organizationList="organizationList"
      :organizationTotalList="organizationTotalList"
    />
    <lan-table
      size="small"
      :config="dataTable"
      :tableData="tableData"
      @search="search"
    >
      <template #type="scope">
        <el-input v-model="scope.row.type"></el-input>
      </template>
      <template #type="scope">
        <div v-if="scope.row.type!=='system'">
          <el-button
            type="text"
            @click="showEdit(scope.row)"
            icon="el-icon-edit"
            size="small"
          >编辑</el-button>
          <el-button
            type="text"
            icon="el-icon-delete"
            @click="remove(scope.row)"
            size="small"
          >删除</el-button>
        </div>

      </template>
    </lan-table>
    <edit
      ref="editComponent"
      :organizationList="organizationList"
      :organizationTotalList="organizationTotalList"
      @refresh="search"
    ></edit>
  </div>
</template>

<script>
import lanTable from '../../../components/lanTable';
import HeaderSearchForm from './headerSearchForm.vue';
import Edit from './edit';
import { Message, MessageBox } from 'element-ui';
import { getUserListApi, deleteUserApi } from '../../../api/user';
import { parseError, parseTime } from '../../../utils';
import { SortType } from '../../../constants/common';
import { getOrganizationListApi } from '../../../api/organization';

export default {
  components: { lanTable, Edit, HeaderSearchForm },
  data() {
    return {
      dataTable: {
        pageSize: 10,
        totalCount: 0,
        currentPage: 1,
        pageSizes: [5, 10, 20, 50, 100],
        sort: {
          orderBy: 'createdAt',
          sortType: SortType.ASC
        },
        columnList: [
          {
            // name: '1',
            type: 'index'
          },
          {
            name: 'username',
            label: '账号'
          },
          {
            name: 'displayName',
            label: '用户名'
          },
          {
            name: 'organization',
            label: '组织'
          },
          {
            name: 'email',
            label: '邮箱'
          },
          {
            name: 'mobile',
            label: '手机号'
          },
          {
            name: 'createdAt',
            label: '创建时间',
            sortable: true
          },
          {
            type: 'slot',
            name: 'type',
            label: '操作'
          }
          // {
          //   type: 'button',
          //   label: '操作',
          //   buttons: [
          //     {
          //       type: 'text',
          //       text: '编辑',
          //       size: 'small',
          //       method: row => {
          //         this.showEdit(row);
          //       }
          //     },
          //     {
          //       type: 'text',
          //       text: '删除',
          //       size: 'small',
          //       method: row => {
          //         this.remove(row);
          //       }
          //     }
          //   ]
          // }
        ]
      },
      tableData: [],
      searchForm: {
        name: '',
        organizationId: '',
        email: '',
        mobile: null,
        btnLoading: false
      },
      roleList: [],
      organizationList: [],
      organizationTotalList: []
    };
  },
  created() {
    this.search();
  },
  methods: {
    remove(row) {
      MessageBox.confirm(`确认删除用户${row.username}吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteUserApi(row.uuid)
            .then(res => {
              if (res.result) {
                Message.success('删除用户成功');
                this.$emit('refresh');
              }
            })
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    },
    showEdit(row) {
      this.$refs.editComponent.showDialog(row);
    },
    async search() {
      try {
        this.searchForm.btnLoading = true;
        const [userListRes, organizationListRes] = await Promise.all([
          getUserListApi(
            this.dataTable.currentPage - 1,
            this.dataTable.pageSize,
            this.dataTable.sort.sortType,
            this.dataTable.sort.orderBy,
            this.searchForm.organizationId,
            this.searchForm.name,
            this.searchForm.email,
            this.searchForm.mobile
          ),
          // getRoleListApi(),
          getOrganizationListApi()
        ]);
        this.tableData = userListRes.data;
        // this.roleList = roleListRes;
        this.organizationList = organizationListRes.children;
        this.setOrganization(this.organizationList);
        this.organizationTotalList = this.organizationTreeToList(this.organizationList);
        this.tableData.forEach(item => {
          item.displayName = item.display_name;
          item.createdAt = parseTime(item.created_at);
          item.organizationIdList = item.organization_id_list;
          item.organization = this.organizationTotalList
            .filter(organization => item.organizationIdList.includes(organization.id))
            .map(organization => organization.name)
            .join(',');
        });
        this.dataTable.totalCount = userListRes.total_count;
      } catch (error) {
        Message.error(parseError(error));
      }
      this.searchForm.btnLoading = false;
    },
    pageSizeChangeHandler() {
      this.currentPage = 1;
      this.search();
    },
    currentPageChangeHandler() {
      this.search();
    },
    getOrganizationName(list, id) {
      const organization = list.find(item => item.id === id);
      if (organization) return organization.name;
      else {
        let childrenList = [];
        list.forEach(item => {
          if (item.children && item.children.length) childrenList = childrenList.concat(item.children);
        });
        if (!childrenList.length) return;
        else return this.getOrganizationName(childrenList, id);
      }
    },
    setOrganization(data) {
      data.forEach(item => {
        if (item.children && !item.children.length) item.children = null;
        else if (item.children && item.children.length) this.setOrganization(item.children);
      });
    },
    organizationTreeToList(data) {
      const result = [];
      data.forEach(item => {
        const loop = data => {
          result.push({
            id: data.id,
            name: data.name
          });
          let child = data.children;
          if (child) {
            for (let i = 0; i < child.length; i++) {
              loop(child[i]);
            }
          }
        };
        loop(item);
      });
      return result;
    }
  }
};
</script>

<style lang="scss" scoped>
.user-list-container {
  .user-list-data-table {
    background-color: #fff;
    padding: 10px;
    margin: 10px 10px 0 10px;
  }
  .paging-footer {
    background-color: #fff;
    margin: 0 10px 10px 10px;
    padding: 0 0 10px 0;
  }
  padding: 10px;
}
</style>
